﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace SharpSoft.WPF.Controls
{
    public class EcllipseGeoDesigner : GeoDesignerBase
    {
        public EcllipseGeoDesigner()
        {
            handler3 = new HandlerThumb() { Shape = HandlerThumbShape.Rhombus };
            this.Handlers.Add(handler3);
            this.Direction = new Vector(100, 0);
            this.Radius = 60;

            handler3.DragDelta += Handler3_DragDelta;
        }



        #region 控制点拖动处理

        private void Handler3_DragDelta(object sender, DragDeltaEventArgs e)
        {
            e.Handled = true;
            var v = (this.Direction / 2).Rotate(Math.PI / 2);//旋转90°得到到宽度控制点的向量
            v.Normalize();
            var v2 = (v * this.Radius);
            var change = new Vector(e.HorizontalChange, e.VerticalChange);//拖动的向量

            if (v2.Length == 0)
            {
                this.Radius = change.Length;
            }
            else
            {
                var prj = v2.Projection(change);//拖动的向量在原始向量上的映射
                this.Radius = (v2 + prj).Length;
            }


        }

        #endregion


        private readonly HandlerThumb handler3;//另一条半轴的手柄


        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);
            if (e.Property == RadiusProperty)
            {
                rePositionHandlers();
            }
        }

        protected override void rePositionHandlers()
        {
            var op = this.OriginalPoint;
            var v = (this.Direction / 2).Rotate(Math.PI / 2);//旋转90°得到到宽度控制点的向量
            v.Normalize();

            var p3 = op + (v * this.Radius);
            handler3.Center = p3;


            this.pathGeometry.Clear();
            var rotate = new RotateTransform(Vector.AngleBetween(new Vector(1, 0), this.Direction), op.X, op.Y);
            EllipseGeometry ell = new EllipseGeometry(op, this.Direction.Length, this.Radius, rotate);
            this.pathGeometry.AddGeometry(ell);
            base.rePositionHandlers();
        }


        #region 个性
        /// <summary>
        /// 与图形方向垂直的另一条半轴的长度
        /// </summary>
        public double Radius
        {
            get { return (double)GetValue(RadiusProperty); }
            set { SetValue(RadiusProperty, value); }
        }

        public static readonly DependencyProperty RadiusProperty =
            DependencyProperty.Register("Radius", typeof(double), typeof(EcllipseGeoDesigner), new PropertyMetadata(default(double)));




        #endregion

    }
}
